package com.aztec.ims.service.dao;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Order;

import com.aztec.ims.domain.PaymentTerms;
import com.aztec.ims.service.response.GenericResponse;
import com.aztec.ims.service.util.HibernateUtil;

public class PaymentTermsDao {
	public GenericResponse createPaymentTerms(PaymentTerms request) {
		com.aztec.ims.service.om.PaymentTerms om = convertRequestToOm(request);

		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		session.save(om);
		session.getTransaction().commit();

		GenericResponse response = new GenericResponse(om.getPymtId()
				.toString());
		return response;
	}

	public List<PaymentTerms> getPaymentTerms() {

		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		Criteria criteria = session.createCriteria(com.aztec.ims.service.om.PaymentTerms.class);
		criteria.addOrder(Order.asc("pymtId"));
		List results = criteria.list();
		session.getTransaction().commit();

		return convertOmToResponse(results);

	}

	private List<PaymentTerms> convertOmToResponse(List results) {
		List<PaymentTerms> response = new ArrayList<PaymentTerms>();

		if (results != null) {
			for (Iterator iter = results.iterator(); iter.hasNext();) {
				com.aztec.ims.service.om.PaymentTerms om = (com.aztec.ims.service.om.PaymentTerms) iter.next();
				PaymentTerms domain = new PaymentTerms();
				domain.setPymtId(om.getPymtId().toString());
				domain.setPymtName(om.getPymtName());
				domain.setDueDays(om.getDueDays());
				domain.setActiveFlag(convertCharacterToBoolean(om.getActiveFlag()));
				response.add(domain);
			}
		}

		return response;
	}

	private com.aztec.ims.service.om.PaymentTerms convertRequestToOm(PaymentTerms request) {

		com.aztec.ims.service.om.PaymentTerms om = new com.aztec.ims.service.om.PaymentTerms();
        om.setPymtName(request.getPymtName());
        om.setDueDays(request.getDueDays());
        om.setActiveFlag(convertBooleanToCharacter(request.getActiveFlag()));
		
		return om;
	}

	private Character convertBooleanToCharacter(Boolean from) {
		Character to = null;
		if (from != null) {
			if (from.booleanValue()) {
				to = new Character('Y');
			} else {
				to = new Character('N');
			}
		}
		return to;
	}

	private Boolean convertCharacterToBoolean(Character from) {
		Boolean to = null;
		if (from != null) {
			if (from.charValue() == 'Y') {
				to = new Boolean(true);
			} else {
				to = new Boolean(false);
			}
		}
		return to;
	}

}
